package com.hrt.datasender.datasent;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import com.hrt.datasender.datasent.serial.SerialManager;
import com.hrt.datasender.datasent.serial.SerialReader;
import com.hrt.datasender.datasent.socket.SocketClientManager;
import com.hrt.datasender.mq.MqKit;
import com.hrt.datasender.mq.model.MqModel;
import com.hrt.datasender.mq.model.PacketModel;

/**
 * Created by Chance on 2017/11/2.
 */
public class DataSenderSerial {

    public static ILog log;

    public static void start() throws Exception {

        log = MyLog.getInstance().getLogger(DataSenderSerial.class.getName());

        try {
            SerialManager.getInstance();
            customerDataMQ();
            customerHeatBeatMQ();
            Thread t1 = new Thread(new SerialReader());
            t1.start();
        } 
        catch (Exception e) {
            throw e;
        }
    }

    public static void main(String[] args) throws Exception {
        DataSenderSerial.start();
    }

    /**
     * 消费数据消息，往外发送
     */
    public static void customerDataMQ() {

        MqKit.consumeMsgFromBizDataMQ(new MqKit.MsgListener() {
            @Override
            public void onReceive(MqModel mqModel) {
                try {

                    PacketModel model = (PacketModel) mqModel;
                    Object msg = model.getMsg();
                    if (msg != null) {
                        SerialManager.getInstance().out.write(msg.toString().getBytes());
                        log.info(model.getIp() + "准备发送数据:" + model.getMsg());
                    }

                    boolean finishSend = SocketClientManager.getInstance().sendMsg(model);
                    if (finishSend) {
                        log.info(model.getIp() + "发送业务消息包成功:" + model.getMsg());
                    }
                } 
                catch (Exception e) {
                    log.error("发送业务消息包错误：", e);
                }
            }
        });
    }

    /**
     * 消费心跳消息，往外发送
     */
    public static void customerHeatBeatMQ() {

        MqKit.consumeMsgFromHeatBeatMQ(new MqKit.MsgListener() {
            @Override
            public void onReceive(MqModel mqModel) {
                try {

                    PacketModel model = (PacketModel) mqModel;
                    Object msg = model.getMsg();
                    if (msg != null) {
                        SerialManager.getInstance().out.write(msg.toString().getBytes());
                        log.info(model.getIp() + "准备发送数据:" + model.getMsg());
                    }

                    boolean finishSend = SocketClientManager.getInstance().sendMsg(model);

                    if (finishSend) {
                        log.info(model.getIp() + "发送心跳包成功:" + model.getMsg());
                    }
                }
                catch (Exception e) {
                    log.error("发送心跳包错误：", e);
                }
            }
        });
    }

}
